<?php

// Application/View/Helper/ControllerName.php

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Javascript extends AbstractHelper
{

    protected $routeMatch;
    protected $pathJs;
    public $init;

    public function __construct( $routeMatch )
    {
        $this->routeMatch = $routeMatch;
        $this->pathJs     = $_SERVER['DOCUMENT_ROOT'] . DS . 'js' . DS . 'scripts' . DS . 'module';

    }

    public function __invoke()
    {
        if ($this->routeMatch) {
            $urlController = $this->routeMatch->getParam( 'controller', 'index' );
            $action        = $this->routeMatch->getParam( 'action', 'index' );
            $arrUrl        = explode( "\\", $urlController );

            $module     = strtolower( $arrUrl[0] );
            $controller = strtolower( $arrUrl[2] );

            echo $this->_hasControllerScript( $module, $controller );
            echo $this->_hasActionScript( $module, $controller, $action );
        }

    }

    private function _hasControllerScript( $module, $controller )
    {
        $controllerFile = $this->pathJs . DS . $module . DS . $controller . '.js';

        if (file_exists( $controllerFile )) {
            $urlControllerFile = "/js/scripts/module/$module/$controller.js";
            $headScript        = new \Zend\View\Helper\HeadScript();
            return $headScript->prependFile( $urlControllerFile );
        }

    }

    private function _hasActionScript( $module, $controller, $action )
    {
        $actionFile = $this->pathJs . DS . $module . DS . $controller . DS . $action . '.js';

        if (file_exists( $actionFile )) {
            $urlActionFile = "/js/scripts/module/$module/$controller/$action.js";
            $headScript    = new \Zend\View\Helper\HeadScript();
            return $headScript->prependFile( $urlActionFile );
        }

    }

}
